import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: 'aaa',
    newId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList (state, data) {
      state.list = data
    },
    changeInputBalue (state, value) {
      state.inputValue = value
    },
    addListData (state) {
      const newList = {
        id: state.newId,
        info: state.inputValue,
        done: false
      }
      state.list.push(newList)
      state.inputValue = ''
      state.newId++
    },
    deleteListItem (state, id) {
      const index = state.list.findIndex(item =>
        item.id === id
      )
      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },
    checkedChange (state, param) {
      const index = state.list.findIndex(item => item.id === param.id)
      if (index !== -1) {
        state.list[index].done = param.status
      }
    },
    clearFinish (state) {
      state.list = state.list.filter(item => item.done === false)
    },
    btnToggle (state, value) {
      state.viewKey = value
    }

  },
  actions: {
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneLen (state) {
      return state.list.filter(item => item.done === false).length
    },
    infoList (state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(item => item.done === true)
      }
      if (state.viewKey === 'done') {
        return state.list.filter(item => item.done === false)
      }
      return state.list
    }
  },
  modules: {
  }
})
